package com.color.admin.common.security.handler;

import com.color.admin.common.core.base.AuthUser;
import com.color.admin.common.core.constant.Constant;
import com.color.admin.common.core.exception.BaseException;
import com.color.admin.common.core.result.ResultCode;
import com.color.admin.common.core.utils.cache.RedisUtils;
import com.color.admin.common.core.utils.web.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author HaiQiu
 * @date 2021/12/10
 * 授权验证处理
 */
@Component
public class AuthHandlerFilter {

    @Autowired
    private RedisUtils redisUtils;

    public boolean authUser(String token) {
        if (!token.startsWith(TokenUtils.PREFIX)) {
            throw new BaseException("token请求头错误");
        } else {
            return TokenUtils.validateToken(token);
        }
    }

    /**
     * 判断是否有权限
     *
     * @param path   请求地址
     * @param method 请求方法
     * @param token  Token
     * @return true有此权限，false无此权限
     */
    public boolean checkAuth(String path, String method, String token) {
        if (Constant.ADMIN.equals(TokenUtils.getUsernameFormToken(token))){
            return true;
        }else if(Constant.ALLOW_APIS.get(path)!=null && Constant.ALLOW_APIS.get(path).equals(method)){
            return true;
        }
        String userId = TokenUtils.getUserIdFormToken(token);
        Object object = redisUtils.get(Constant.USER_AUTH + userId);
        List<AuthUser> authUsers = null;
        if (object instanceof ArrayList<?>){
            authUsers = (List<AuthUser>)object;
        }
        if (CollectionUtils.isEmpty(authUsers)) {
            throw new BaseException(ResultCode.AUTH_EXITS);
        }
        for (AuthUser authUser : authUsers) {
            if (authUser.getMethod()==null || authUser.getPath()==null){
                continue;
            }
            if (authUser.getMethod().equals(method) && authUser.getPath().equals(path)) {
                return true;
            }
        }
        return false;
    }
}
